package com.redpack.quick.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by shuttle on 4/8/18.
 */
public class OkHttpUtils {
    //    @Autowired
    //    @Qualifier(value = "longHttpClient")
    //    private static OkHttpClient longHttpClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtils.class);

    public final static int       CONNECT_TIMEOUT = 30;
    public final static int       READ_TIMEOUT    = 30;
    public final static int       WRITE_TIMEOUT   = 30;
    public static final MediaType JSON_TYPE       = MediaType.parse("application/json; charset=utf-8");

    public static String sendPost(String url, Map<String, String> paramMap) {
        return sendPost(url, paramMap, null);
    }

    private static class InnerOKHttp {
        private static OkHttpClient client = new OkHttpClient();
    }

    public static OkHttpClient getClient() {
        return InnerOKHttp.client;
    }

    public static String sendPost(String url, Map<String, String> paramMap, Map<String, String> header) {
        OkHttpClient client = getClient();
        client.newBuilder().connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        //        String jsonString = JSONObject.toJSONString(paramMap);
        //        RequestBody body = RequestBody.create(JSON_TYPE, paramMap.toString());
        FormBody.Builder builder = new FormBody.Builder();

        if (paramMap != null) {
            String paramName = null;
            String paramValue = null;
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                paramName = entry.getKey();
                paramValue = entry.getValue();
                builder.add(paramName, paramValue);
            }
        }
        String headerName = "user-agent";
        String headeValue = "nodata";
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                headerName = entry.getKey();
                headeValue = entry.getValue();
            }
        }
        //        FormBody.Builder bilder = new FormBody.Builder();
        FormBody body = builder.build();
        Request request = new Request.Builder().url(url).addHeader(headerName, headeValue).post(body).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                LOGGER.info("请求相应异常");
                return "服务异常";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String okHttpGet(String url){
        try {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
            Request request = new Request.Builder()
                    .addHeader("content-type", "application/json")
                    .url(url)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象
            if (response.isSuccessful()) {
                return response.message();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static boolean okHttpPost(FormBody.Builder bilder, HttpServletRequest request, OkHttpClient longHttpClient) {
        //userstatus相关
        String userAgent = request.getHeader("user-agent");
        RequestBody body = bilder.build();
        Request req = new Request.Builder().url("https://api.geinihua.com/internal/userinfo/updateStatus").post(body)
                .addHeader("user-agent", userAgent).build();
        try {
            Response respe = longHttpClient.newCall(req).execute();
            String strResponse = null;
            if (respe.isSuccessful()) {
                strResponse = respe.body().string();
                Map<String, String> ret = JsonUtils.objectFromJson(strResponse,
                        new TypeReference<Map<String, String>>() {
                        });
                //请求成功
                if (ret != null && "1".equals(ret.get("code"))) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (IOException e) {
            LOGGER.info("okhttp调用失败" + e);
            return false;
        }
    }
}
